package com.power.sifa.ocr.controller;

import com.plf.common.domain.ResponseDTO;
import com.power.sifa.ocr.api.OcrBaiduFeign;
import com.power.sifa.ocr.service.OcrBaiduService;
import com.power.sifa.util.Base64Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

@Slf4j
@RestController
@Api(value = "OcrBaiduController", tags = {"百度Ocr识别接口"})
public class OcrBaiduController implements OcrBaiduFeign {

    @Autowired(required = false)
    private OcrBaiduService ocrBaiduService;

    @ApiOperation("Ocr识别文字信息")
    public ResponseDTO OcrBaidu(String url) {
        File file = new File(url);
        if (!file.isFile()) {
            return ResponseDTO.wrap(500, "路径有误，请上传文件！");
        }
        String fileType = ocrBaiduService.detectFileType(url);
        System.out.println(fileType);

        String result = null;
        // 根据fileType判断是PDF还是图片
        if (fileType.equals("application/pdf")) {
            result = ocrBaiduService.readPDF(url);
        } else if (fileType.startsWith("image/")) {
            result = ocrBaiduService.readImage(url);
        } else {
            // 其他类型文件
            return ResponseDTO.wrap(500, "文件格式有误，请上传图片或者PDF！");
        }
        return ResponseDTO.succData(result);
    }

    @Override
    public ResponseDTO OcrBaidu(MultipartFile file) {
        File convertedFile = new File(file.getOriginalFilename());
        // 判断转换后的文件是否存在
        if (file.isEmpty()) {
            return ResponseDTO.wrap(500, "文件转换失败，请上传有效文件！");
        }
        String result = "";
        try {
            result = ocrBaiduService.readFile(file);
        } catch (Exception e) {
            return ResponseDTO.wrap(500, e.getMessage());
        }
        log.info("结果:{}", result);
        return ResponseDTO.succData(result);
    }

    @Override
    public ResponseDTO OcrByAttachmentid(String attachmentid) {
        if (attachmentid == null || attachmentid.equals("")) {
            return ResponseDTO.wrap(500, "请传入正确的参数！");
        }
        try {
            return ResponseDTO.succData(ocrBaiduService.readByAttachmentid(attachmentid));
        } catch (Exception e) {
            return ResponseDTO.wrap(500, e.getMessage());
        }
    }

    private File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File convertedFile = new File(file.getOriginalFilename());
        file.transferTo(convertedFile);
        return convertedFile;
    }
}
